from pyproj import Proj
from lxml import etree
from StringIO import StringIO
import math

def openToSumo(openCoordinates):	
	xOffset = -728301.15
	yOffset = -3750517.90
	p = Proj("+proj=utm +zone=36 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
	x,y = p(openCoordinates["lon"],openCoordinates["lat"])
	x = x + xOffset
	y = y + yOffset
	
	sumoCoordinates = {"x" : x, "y" : y}
	print sumoCoordinates
	return sumoCoordinates

def sumoToOpen(sumoCoordinates):
	xOffset = -728301.15
	yOffset = -3750517.90
	p = Proj("+proj=utm +zone=36 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
	x1 = sumoCoordinates["x"] - xOffset
	y1 = sumoCoordinates["y"] - yOffset
	lon,lat = p(x1,y1,inverse=True)
	openCoordinates = {"lon" : lon, "lat" : lat}
	print openCoordinates
	return openCoordinates	

openCoordinates = {"lon":35.47468,"lat":33.899884} 
print openCoordinates;
sumoCoordinates = openToSumo(openCoordinates)
openCoordinatesReversed = sumoToOpen(sumoCoordinates)


def getSumoJunctions(netFileXml):
	networkFile= netFileXml;
	f= open(networkFile);
	xml = f.read();
	f.close();
	tree = etree.parse(StringIO(xml));
	context = etree.iterparse(StringIO(xml));
	i=0;
	result = "a";
	sumoCoord = [];
	for action, elem in context:
		i=i+1;
		if (elem.tag == "junction"):
			coord  = elem.get("x"), elem.get("y"), elem.get("incLanes").replace(':','');
			print coord[2];
			sumoCoord.append(coord);
	
	return sumoCoord;

def findClosest(empCoord,netFileXml):
	
	coordinateList = getSumoJunctions(netFileXml);
	print coordinateList ;
	
	empX = empCoord[0];
	empY = empCoord[1];
	closestPoint = 0,0;
	#print empY;
	smallestDist = float("inf");
	closestY = 0;
	for netCoord in coordinateList:
		netX=float(netCoord[0]);
		netY=float(netCoord[1]);
		currentDist = math.sqrt(((netX-empX)**2)+((netY-empY)**2));
		if (currentDist < smallestDist):
			smallestDist = currentDist;
			closestPoint = netX, netY;
	
	#print smallestDist;
	#print closestPoint;			

X = raw_input("X=");
Y= raw_input("Y=");
open = sumoToOpen({"x":float(X),"y":float(Y)});
print open;
print openToSumo(open);
X = raw_input("X=");
Y= raw_input("Y=");
print sumoToOpen({"x":float(X),"y":float(Y)});
#empCoord = 2000,3000;			
#findClosest(empCoord,"BeirutMap1.net.xml");
